<script lang="ts" setup>
import { onMounted, ref, computed } from 'vue';
import { columns } from '@/views/kg/knowledge/utils/columns';
import PureTableBar from '@/components/TableBar/src/bar';
import PureTable from '@pureadmin/table';
import {
  deleteIds,
  onAdd,
  onAssignPrerequisitesToKnowledge,
  onDelete,
  onDeleteBatch,
  onSearch,
  onUpdate,
  knowledgeDialogVisible,
  assignPrerequisitesDialogVisible,
  currentKnowledgeId,
  operationType,
} from '@/views/kg/knowledge/utils/hooks';
import Delete from '@iconify-icons/ep/delete';
import EditPen from '@iconify-icons/ep/edit-pen';
import Refresh from '@iconify-icons/ep/refresh';
import { useRenderIcon } from '@/components/CommonIcon/src/hooks';
import AddFill from '@iconify-icons/ri/add-circle-line';
import { useKnowledgeStore } from '@/store/kg/knowledge';
import KnowledgeDialog from '@/views/kg/knowledge/knowledge-dialog.vue';
import { usePublicHooks } from '@/views/hooks';
import { auth } from '@/views/kg/knowledge/utils/auth';
import { hasAuth } from '@/router/utils';
import Auth from '@/components/Auth/index.vue';
import { selectUserinfo } from '@/components/Table/Userinfo/columns';
import AssignPrerequisitesToKnowledge from '@/views/kg/knowledge/assign-prerequisites-to-knowledge.vue';

const knowledgeStore = useKnowledgeStore();
const { switchStyle } = usePublicHooks();
const tableRef = ref();
const formRef = ref();
const knowledgeDialogRef = ref();
const assignPrerequisitesRef = ref();
const courseSearchText = ref('');

// 根据搜索条件过滤课程列表
const filteredCourseList = computed(() => {
  if (!courseSearchText.value) {
    return knowledgeStore.courseList;
  }

  const searchLower = courseSearchText.value.toLowerCase();
  return knowledgeStore.courseList.filter(course =>
    course.name.toLowerCase().includes(searchLower) ||
    (course.code && course.code.toLowerCase().includes(searchLower))
  );
});

/** 保存知识点前置知识点分配 */
const saveKnowledgePrerequisites = async () => {
  if (assignPrerequisitesRef.value) {
    await knowledgeStore.updateKnowledgePrerequisites(currentKnowledgeId.value, assignPrerequisitesRef.value.assignPrerequisites);
    assignPrerequisitesDialogVisible.value = false;
    await onSearch();
  }
};

/** 当前页改变时 */
const onCurrentPageChange = async (value: number) => {
  knowledgeStore.pagination.currentPage = value;
  await onSearch();
};

/** 当分页发生变化 */
const onPageSizeChange = async (value: number) => {
  knowledgeStore.pagination.pageSize = value;
  await onSearch();
};

/** 选择多行 */
const onSelectionChange = (rows: Array<any>) => {
  deleteIds.value = rows.map((row: any) => String(row.nodeId));
};

/** 重置表单 */
const resetForm = async () => {
  if (!formRef.value) return;
  formRef.value.resetFields();
  knowledgeStore.resetForm();
  await onSearch();
};

/** 选择课程 */
const handleCourseSelect = async (courseId: string | undefined) => {
  knowledgeStore.setSelectedCourse(courseId);
  await onSearch();
};

onMounted(async () => {
  // 加载课程列表
  await knowledgeStore.getCourseList();
  // 加载知识点列表
  await onSearch();
});
</script>

<template>
  <div class="main flex">
    <!-- 左侧课程列表 -->
    <div class="left-panel w-[260px] border-r border-gray-200 p-4 overflow-auto">
      <div class="mb-4 text-lg font-medium">课程列表</div>

      <!-- 课程搜索框 -->
      <div class="mb-4">
        <el-input
          v-model="courseSearchText"
          placeholder="搜索课程..."
          :prefix-icon="useRenderIcon('ri:search-line')"
          clearable
          class="course-search"
        >
        </el-input>
      </div>

      <!-- 自定义课程列表替代 el-menu -->
      <div class="course-list">
        <div
          class="course-item"
          :class="{'is-active': !knowledgeStore.selectedCourseId}"
          @click="handleCourseSelect('')"
        >
          <span>全部课程</span>
        </div>

        <div
          v-for="course in filteredCourseList"
          :key="course.nodeId"
          class="course-item"
          :class="{'is-active': String(course.nodeId) === String(knowledgeStore.selectedCourseId)}"
          @click="handleCourseSelect(String(course.nodeId))"
        >
          <span>{{ course.name }}</span>
        </div>
      </div>
    </div>

    <!-- 右侧知识点管理 -->
    <div class="right-panel flex-1 overflow-hidden">
      <!-- 搜索表单 -->
      <el-form ref="formRef" :inline="true" :model="knowledgeStore.form" class="search-form bg-bg_color w-[99/100] pl-8 pt-[12px] overflow-auto">
        <el-form-item label="知识点名称" prop="name">
          <el-input v-model="knowledgeStore.form.name" placeholder="请输入知识点名称" class="!w-[180px]" clearable />
        </el-form-item>
        <el-form-item label="知识点概述" prop="summary">
          <el-input v-model="knowledgeStore.form.summary" placeholder="请输入知识点概述" class="!w-[180px]" clearable />
        </el-form-item>
        <el-form-item label="难度级别" prop="level">
          <el-select v-model="knowledgeStore.form.level" placeholder="请选择难度级别" class="!w-[180px]" clearable>
            <el-option label="基础" :value="1" />
            <el-option label="简单" :value="2" />
            <el-option label="一般" :value="3" />
            <el-option label="困难" :value="4" />
            <el-option label="进阶" :value="5" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button :icon="useRenderIcon('ri:search-line')" :loading="knowledgeStore.loading" type="primary" @click="onSearch">
            搜索
          </el-button>
          <el-button :icon="useRenderIcon(Refresh)" @click="resetForm">
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <PureTableBar :columns="columns" title="知识点管理" @fullscreen="tableRef?.setAdaptive()" @refresh="onSearch">
        <template #buttons>
          <el-button v-if="hasAuth(auth.add)" :icon="useRenderIcon(AddFill)" type="primary" @click="onAdd">
            新增
          </el-button>

          <!-- 批量删除按钮 -->
          <el-button v-if="hasAuth(auth.deleted)" :disabled="!(deleteIds.length > 0)" :icon="useRenderIcon(Delete)" type="danger" @click="onDeleteBatch">
            批量删除
          </el-button>
        </template>

        <template v-slot="{ size, dynamicColumns }">
          <pure-table
            ref="tableRef"
            :adaptiveConfig="{ offsetBottom: 96 }"
            :columns="dynamicColumns"
            :data="knowledgeStore.datalist"
            :header-cell-style="{ background: 'var(--el-fill-color-light)', color: 'var(--el-text-color-primary)' }"
            :loading="knowledgeStore.loading"
            :pagination="knowledgeStore.pagination"
            :size="size"
            adaptive
            align-whole="center"
            border
            highlight-current-row
            row-key="nodeId"
            showOverflowTooltip
            table-layout="auto"
            @page-size-change="onPageSizeChange"
            @selection-change="onSelectionChange"
            @page-current-change="onCurrentPageChange"
          >
            <!-- 创建人插槽 -->
            <template #createUser="{ row }">
              <el-button v-show="row.createdById" link type="primary" @click="selectUserinfo(row.createdById)">
                {{ row.createdByUsername }}
              </el-button>
            </template>

            <!-- 更新人插槽 -->
            <template #updateUser="{ row }">
              <el-button v-show="row.updatedById" link type="primary" @click="selectUserinfo(row.updatedById)">
                {{ row.updatedByUsername }}
              </el-button>
            </template>

            <!-- 标签插槽 -->
            <template #tags="{ row }">
              <div class="tags-container">
                <el-tag
                  v-for="tag in row.tags"
                  :key="tag"
                  class="tag-item"
                  size="small"
                  effect="plain"
                >
                  {{ tag }}
                </el-tag>
                <span v-if="!row.tags || row.tags.length === 0" class="text-gray-400">无标签</span>
              </div>
            </template>

            <!-- 难度级别插槽 -->
            <template #level="{ row }">
              <el-tag v-if="row.level === 1" type="info">基础</el-tag>
              <el-tag v-else-if="row.level === 2" type="success">简单</el-tag>
              <el-tag v-else-if="row.level === 3" type="warning">一般</el-tag>
              <el-tag v-else-if="row.level === 4" type="danger">困难</el-tag>
              <el-tag v-else-if="row.level === 5" type="primary">进阶</el-tag>
              <span v-else>{{ row.level }}</span>
            </template>

            <!-- 操作列 -->
            <template #operation="{ row }">
              <el-button v-if="hasAuth(auth.update)" :icon="useRenderIcon(EditPen)" :size="size" class="reset-margin" link type="primary" @click="onUpdate(row)">
                编辑
              </el-button>
              <el-button v-if="hasAuth(auth.updatePrerequisites)" :icon="useRenderIcon('ri:list-check')" :size="size" class="reset-margin" link type="primary" @click="onAssignPrerequisitesToKnowledge(row)">
                前置知识
              </el-button>
              <el-button v-if="hasAuth(auth.deleted)" :icon="useRenderIcon(Delete)" :size="size" class="reset-margin" link type="primary" @click="onDelete(row)">
                删除
              </el-button>
            </template>
          </pure-table>
        </template>
      </PureTableBar>

      <!-- 知识点编辑对话框 -->
      <el-dialog
        v-model="knowledgeDialogVisible"
        :destroy-on-close="true"
        :title="operationType === 'add' ? '添加知识点' : '编辑知识点'"
        width="500px"
      >
        <KnowledgeDialog ref="knowledgeDialogRef" />
        <template #footer>
          <el-button @click="knowledgeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="async () => {
            const result = await knowledgeDialogRef?.onSaveKnowledge(knowledgeDialogRef.$refs.formRef);
            if (result) {
              knowledgeDialogVisible = false;
              await onSearch();
            }
          }">确认</el-button>
        </template>
      </el-dialog>

      <!-- 添加前置知识点对话框 -->
      <el-dialog
        v-model="assignPrerequisitesDialogVisible"
        :destroy-on-close="true"
        title="设置前置知识点"
        width="800px"
      >
        <AssignPrerequisitesToKnowledge ref="assignPrerequisitesRef" :knowledge-id="currentKnowledgeId" />
        <template #footer>
          <el-button @click="assignPrerequisitesDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveKnowledgePrerequisites">确认</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.main {
  width: 100%;
  height: 100%;
}

.left-panel {
  height: 100%;
  background-color: var(--el-bg-color);
  border-right: 1px solid var(--el-border-color-light);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.course-search {
  width: 100%;
  margin-bottom: 8px;
}

.course-list {
  display: flex;
  flex-direction: column;
  gap: 4px;
  max-height: calc(100vh - 250px);
  overflow-y: auto;
}

.course-item {
  padding: 10px 16px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid transparent;
  font-size: 14px;

  &.is-active {
    background-color: #ecf5ff !important;
    color: var(--el-color-primary) !important;
    font-weight: 600;
    border-color: var(--el-color-primary-light-5);
    position: relative;

    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 0;
      bottom: 0;
      width: 4px;
      background-color: var(--el-color-primary);
      border-radius: 2px;
    }
  }

  &:hover:not(.is-active) {
    background-color: #f5f7fa;
    color: var(--el-color-primary);
  }
}

.right-panel {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding-left: 12px;
}

.search-form {
  padding: 18px 0 18px 20px;
  margin-bottom: 8px;
  border-radius: 4px;
  background-color: var(--el-bg-color-overlay);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.03);
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.tag-item {
  margin-right: 4px;
  margin-bottom: 4px;
}

.text-gray-400 {
  color: #909399;
  font-size: 12px;
  font-style: italic;
}
</style>
